<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\AiRole;

class AiRoleController extends BaseController
{
    /**
     * 获取AI角色列表
     */
    public function index(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);

        $roles = AiRole::where('user_id', $user->id)
            ->order('is_default', 'desc')
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        return json([
            'status' => 200,
            'data' => [
                'total' => $roles->total(),
                'current_page' => $roles->currentPage(),
                'last_page' => $roles->lastPage(),
                'roles' => $roles->items()
            ]
        ]);
    }

    /**
     * 创建AI角色
     */
    public function create(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证数据
        $validate = validate([
            'name' => 'require|max:50',
            'description' => 'max:1000',
            'avatar' => 'max:255'
        ]);

        if (!$validate->check($data)) {
            return json(['status' => 400, 'message' => $validate->getError()]);
        }

        try {
            $role = new AiRole;
            $role->user_id = $user->id;
            $role->name = $data['name'];
            $role->description = $data['description'] ?? '';
            $role->avatar = $data['avatar'] ?? '';
            $role->is_default = $data['is_default'] ?? 0;
            $role->create_time = time();
            $role->update_time = time();
            
            // 如果设置为默认角色，需要将其他角色设为非默认
            if ($role->is_default) {
                AiRole::where('user_id', $user->id)
                    ->where('is_default', 1)
                    ->update(['is_default' => 0]);
            }
            
            $role->save();

            return json([
                'status' => 200,
                'message' => '创建成功',
                'data' => $role
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新AI角色
     */
    public function update(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $roleId = $request->param('id');
        $data = $request->post();

        $role = AiRole::where('id', $roleId)
            ->where('user_id', $user->id)
            ->find();

        if (!$role) {
            return json(['status' => 404, 'message' => '角色不存在或无权限']);
        }

        try {
            if (isset($data['name'])) {
                $role->name = $data['name'];
            }
            if (isset($data['description'])) {
                $role->description = $data['description'];
            }
            if (isset($data['avatar'])) {
                $role->avatar = $data['avatar'];
            }
            if (isset($data['is_default'])) {
                $role->is_default = $data['is_default'];
                if ($role->is_default) {
                    AiRole::where('user_id', $user->id)
                        ->where('id', '<>', $roleId)
                        ->where('is_default', 1)
                        ->update(['is_default' => 0]);
                }
            }
            $role->update_time = time();
            $role->save();

            return json([
                'status' => 200,
                'message' => '更新成功',
                'data' => $role
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除AI角色
     */
    public function delete(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $roleId = $request->param('id');

        $role = AiRole::where('id', $roleId)
            ->where('user_id', $user->id)
            ->find();

        if (!$role) {
            return json(['status' => 404, 'message' => '角色不存在或无权限']);
        }

        // 不允许删除默认角色
        if ($role->is_default) {
            return json(['status' => 400, 'message' => '不能删除默认角色']);
        }

        try {
            $role->delete();
            return json(['status' => 200, 'message' => '删除成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取AI角色详情
     */
    public function detail(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $roleId = $request->param('id');
        
        if (empty($roleId)) {
            return json(['status' => 400, 'message' => '角色ID不能为空']);
        }

        try {
            $role = AiRole::where('id', $roleId)
                ->where('user_id', $user->id)
                ->find();

            if (!$role) {
                return json(['status' => 404, 'message' => '角色不存在或无权限']);
            }

            // 格式化角色数据
            $data = [
                'id' => $role->id,
                'user_id' => $role->user_id,
                'name' => $role->name,
                'description' => $role->description,
                'avatar' => $role->avatar,
                'is_default' => $role->is_default,
                'create_time' => $role->create_time,
                'update_time' => $role->update_time
            ];

            return json([
                'status' => 200,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('获取AI角色详情失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取角色详情失败：' . $e->getMessage()]);
        }
    }
} 